#include "udp_client.hpp"
#include "err.hpp"

using namespace std;

static void usage(string proc)
{
    cout << "Usage\n\t" << proc << " serverIp serverPort" << endl;
}

// 收数据
void* Recv(void*args)
{
    int sock=*((int*)args);
    char buffer[1024];
    while (true)
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        socklen_t len = sizeof(server);

        // 缓冲区需要预留\0的位置
        int n = recvfrom(sock, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&server, &len);
        if (n > 0)
            buffer[n] = '\0';
        else
            continue;

        std::cout<<buffer<<std::endl;
    }
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        usage(argv[0]);
        exit(USAGE_ERR);
    }

    // 提取服务器信息
    string serverIp = argv[1];
    uint16_t serverPort = atoi(argv[2]);

    // 创建套接字
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0)
    {
        cerr << "create sock error," << strerror(errno) << endl;
        exit(SOCKET_ERR);
    }
    std::cerr << "create socket success: " << sock << std::endl;

    //发数据
    pthread_t pid;
    pthread_create(&pid,nullptr,Recv,&sock); 

    // 客户端不需要自己bind
    struct sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverIp.c_str());
    server.sin_port = htons(serverPort);
    //收数据
    while (true)
    {
        cerr << "please enter your message# ";
        string message;
        getline(cin, message);

        int m=sendto(sock, message.c_str(), message.size(), 0, (struct sockaddr *)&server, sizeof(server));
    }
    return 0;
}